package my.dict.v01;	

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Stack;

import my.dict.data.Parse1;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class Wordlist extends Activity {

	ListView lv;
	AutoCompleteTextView textView;
	Button buttonBack;
	
	static Stack<String> stackHistory;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.wordlist);
		
		//get the Map <K, V>
		Parse1 parse1 = new Parse1();
		final Map<String, String> mapWords = parse1.getMapWords();
	
		String[] words = new String[mapWords.size()];
		int i = 0;
		for (Entry<String, String> entry : mapWords.entrySet()) {
			words[i++] = entry.getKey().toLowerCase();
		}		

		final List<String> wordList = Arrays.asList(words);			
		
		stackHistory = new Stack<String>();
		//stackHistory.setSize(10);
				
		
		 textView = (AutoCompleteTextView) findViewById(R.id.ACTV_search);
	        final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
	                android.R.layout.simple_dropdown_item_1line, words);
	        textView.setAdapter(adapter);
	        
	        textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icon_search, 
	        		0,0,0);
		
	        textView.setBackgroundColor(Color.WHITE);
	        textView.setPadding(5,0,0,0);
	        
		
		lv = (ListView)findViewById(R.id.listview_words);
	
		lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, words));

		  lv.setTextFilterEnabled(false);
  
		  
		  lv.setOnItemClickListener(new OnItemClickListener() {
		    public void onItemClick(AdapterView<?> parent, View view,
		        int position, long id) {
		    		    	
		    	final String word = (((TextView) view).getText()).toString();
		    	String def = mapWords.get(((TextView) view).getText());
		    	
		    	//sync AutocCompleteTextView
		    	textView.setText(word);
		    	textView.dismissDropDown();
		    	textView.clearListSelection();

		    	//push to stackHistory if possible
	    		
		    	if(stackHistory.size() < historysize() && !stackHistory.contains(word))
		    		stackHistory.push(word);
		    	else {
		    		stackHistory.removeElementAt(0);
		    		stackHistory.push(word);
		    	}			    					    	
		    	
		    	
		    	if(stackHistory.empty() == true) 
		    		buttonBack.setEnabled(false);
		    	else
		    		buttonBack.setEnabled(true);				    	
	    	
		    	AlertDialog builder = new AlertDialog.Builder(Wordlist.this)
		    	.setIcon(R.drawable.icon_dict)
                .setTitle(word)                
                .setMessage(def.trim())
                .setPositiveButton(R.string.dialog_pronunciation_msg, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {                    	
                    	Main.mTts.speak(word, TextToSpeech.QUEUE_ADD, null);                    	
                    	
                        //User clicked Something so do some stuff 
                    }                    
                })                
                .setNeutralButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {    
                        /* User clicked OK so do some stuff */
                    }
                })
                .create();  	
    	

		    	builder.show();
		    	
		      //pronounce it
		      if(pronounce())
		    	  Main.mTts.speak(word, TextToSpeech.QUEUE_ADD, null);
		      
		    }
		  });  
 		
		  
		  textView.setOnItemClickListener(new OnItemClickListener() {
			    public void onItemClick(AdapterView<?> parent, View view,
				        int position, long id) {
				    		    	
				    	final String word = (((TextView) view).getText()).toString();
				    	String def = mapWords.get(((TextView) view).getText());
				    	
				    	//sync ListView
				    	lv.setSelection(wordList.indexOf(word));

				    	//push to stackHistory if possible
			    				    		
				    	if(stackHistory.size() < historysize() && !stackHistory.contains(word))
				    		stackHistory.push(word);
				    	else {
				    		stackHistory.removeElementAt(0);
				    		stackHistory.push(word);
				    	}			    					    	

				    	if(stackHistory.empty() == true) 
				    		buttonBack.setEnabled(false);
				    	else
				    		buttonBack.setEnabled(true);				    				    	
				    	
				    	AlertDialog builder = new AlertDialog.Builder(Wordlist.this)
				    	.setIcon(R.drawable.icon_dict)
		                .setTitle(word)                
		                .setMessage(def.trim())
		                .setPositiveButton(R.string.dialog_pronunciation_msg, new DialogInterface.OnClickListener() {
		                    public void onClick(DialogInterface dialog, int whichButton) {                    	
		                    	Main.mTts.speak(word, TextToSpeech.QUEUE_ADD, null);                    	
		                    	
		                        //User clicked Something so do some stuff 
		                    }                    
		                })                
		                .setNeutralButton("OK", new DialogInterface.OnClickListener() {
		                    public void onClick(DialogInterface dialog, int whichButton) {    
		                        /* User clicked OK so do some stuff */
		                    }
		                })
		                .create();  	
		    	

				    	builder.show();
				    	
				      //pronounce it
				      if(pronounce())
				    	  Main.mTts.speak(word, TextToSpeech.QUEUE_ADD, null);
				      
				    }
				  });  
		  
			//buttonBack processing
			buttonBack = (Button)findViewById(R.id.buttonBack);
			buttonBack.setEnabled(false);
			
			buttonBack.setOnClickListener(new View.OnClickListener() {
	            public void onClick(View v) {
	                // Perform action on click
	            	
	            	String word;
	            	
	            	if(stackHistory.empty() == true) {
	            		buttonBack.setEnabled(false);
	            	}
	            	else {       	          		
	            		buttonBack.setEnabled(true);
		            	if (stackHistory.capacity() > 0) {
		            		word = stackHistory.pop();
	
					    	//sync ListView
					    	lv.setSelection(wordList.indexOf(word));
					    	
					    	//sync AutocCompleteTextView
					    	textView.setText(word);
					    	textView.dismissDropDown();
					    	textView.clearListSelection();			    	
		            		
		            	}
		            	
	            	}
	            	
	            }
	        });		  
		  
		}	

	public boolean pronounce() {
        SharedPreferences prefs = getSharedPreferences("my.dict.v01_preferences", 0); 
        return prefs.getBoolean( 
                this.getResources().getString(R.string.pref_pronunciation),                
                true);        
	        
	}
	
	public int historysize() {
        SharedPreferences prefs = getSharedPreferences("my.dict.v01_preferences", 0); 
        return Integer.parseInt(prefs.getString( 
                this.getResources().getString(R.string.pref_history),                
                "10"));        
		
	}
	
}
